import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { ssoLogin, localLogin } from '@/services/Application'
import { useUserStore } from '@/stores/modules/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'

NProgress.configure({ showSpinner: false }) // NProgress Configuration取消右上角旋转图标
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          component: () => import('@/views/home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/application',
          component: () => import('@/views/application/index.vue'),
          meta: {
            title: '应用中心'
          }
        },
        {
          path: '/information',
          component: () => import('@/views/information/index.vue'),
          meta: {
            title: '消息中心'
          }
        },
        {
          path: '/message',
          component: () => import('@/views/message/index.vue'),
          meta: {
            title: '资讯中心'
          }
        }
      ]
    }
  ]
})
// 访问权限控制
router.beforeEach(async (to) => {
  document.title = `农林大学-${to.meta.title || ''}`
  //开启进度条
  NProgress.start()
  // 用户仓库
  const store = useUserStore()
  try {
    if (!store.user?.token) {
      //const res = await localLogin()
      //store.setUser(res.token)
      window.location.href =
        'http://localhost:8084' + '/redirectLogin?targetUrl=' + '/home/index'
    }
  } catch (e) {
    //提示联系管理人员
    ElMessage.error('登录失败，请联系管理员')
  }

  // 不需要登录的页面，白名单
  // const wihteList = ['/login']
  // 如果没有登录且不在白名单内，去登录
  // if (!store.user?.token && !whiteList.includes(to.path)) {
  //   return '/login'
  // }
  // 否则不做任何处理
})
//后置路由守卫
router.afterEach((to) => {
  //关闭进度条
  NProgress.done()
  //修改页面标题
  document.title = `农林大学-${to.meta.title || ''}`
})
export default router
